import React, { useState, useEffect } from 'react'
import { clsx } from 'clsx'
import type { RoleOption, RoleTrait } from './RoleSelector'

interface RoleEditorProps {
  isOpen: boolean
  onClose: () => void
  onSave: (role: RoleCreateData) => Promise<void>
  editingRole?: RoleOption | null
  className?: string
}

export interface RoleCreateData {
  name: string
  title: string
  input_spec: string
  output_spec: string
  custom_traits?: RoleTrait[]
}

// 特征建议
const traitSuggestions = {
  common: [
    { key: "背景", examples: ["10年经验", "硅谷工程师", "谷歌专家"] },
    { key: "性格", examples: ["严谨细致", "幽默风趣", "温和耐心"] },
    { key: "专长", examples: ["性能优化", "架构设计", "数据分析"] },
    { key: "口头禅", examples: ["让我们一步步来", "代码即文档", "简洁优先"] },
    { key: "原则", examples: ["用户至上", "质量第一", "安全为本"] }
  ]
}

export const RoleEditor: React.FC<RoleEditorProps> = ({
  isOpen,
  onClose,
  onSave,
  editingRole = null,
  className = ''
}) => {
  const [formData, setFormData] = useState<RoleCreateData>({
    name: '',
    title: '',
    input_spec: '',
    output_spec: '',
    custom_traits: []
  })
  
  const [systemPromptPreview, setSystemPromptPreview] = useState('')
  const [testInput, setTestInput] = useState('')
  const [testOutput, setTestOutput] = useState('')
  const [testLoading, setTestLoading] = useState(false)
  const [saving, setSaving] = useState(false)
  const [errors, setErrors] = useState<Record<string, string>>({})
  const [activeTab, setActiveTab] = useState<'basic' | 'traits' | 'test'>('basic')

  // 初始化编辑数据
  useEffect(() => {
    if (editingRole) {
      setFormData({
        name: editingRole.name,
        title: editingRole.title || '',
        input_spec: editingRole.input_spec || '',
        output_spec: editingRole.output_spec || '',
        custom_traits: editingRole.custom_traits || []
      })
    } else {
      setFormData({
        name: '',
        title: '',
        input_spec: '',
        output_spec: '',
        custom_traits: []
      })
    }
    setSystemPromptPreview('')
    setTestInput('')
    setTestOutput('')
    setErrors({})
  }, [editingRole, isOpen])

  // 生成系统提示词预览
  useEffect(() => {
    if (formData.name && formData.input_spec && formData.output_spec) {
      generateSystemPromptPreview()
    }
  }, [formData])

  const generateSystemPromptPreview = async () => {
    try {
      const response = await fetch('/api/roles/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.name,
          input_spec: formData.input_spec,
          output_spec: formData.output_spec,
          custom_traits: formData.custom_traits,
          input: '预览'
        })
      })
      
      const data = await response.json()
      if (data.success) {
        setSystemPromptPreview(data.system_prompt || '')
      }
    } catch (error) {
      console.error('Failed to generate preview:', error)
    }
  }

  const validateForm = (): boolean => {
    const newErrors: Record<string, string> = {}

    if (!formData.name.trim()) {
      newErrors.name = '角色名称不能为空'
    } else if (formData.name.trim().length < 2 || formData.name.trim().length > 20) {
      newErrors.name = '角色名称长度应在2-20字符之间'
    }

    if (!formData.title.trim()) {
      newErrors.title = '职业名称不能为空'
    } else if (formData.title.trim().length < 2 || formData.title.trim().length > 15) {
      newErrors.title = '职业名称长度应在2-15字符之间'
    }

    if (!formData.input_spec.trim()) {
      newErrors.input_spec = '输入规范不能为空'
    } else if (formData.input_spec.trim().length > 800) {
      newErrors.input_spec = '输入规范不能超过800字符'
    }

    if (!formData.output_spec.trim()) {
      newErrors.output_spec = '输出规范不能为空'
    } else if (formData.output_spec.trim().length > 800) {
      newErrors.output_spec = '输出规范不能超过800字符'
    }

    if (formData.custom_traits && formData.custom_traits.length > 3) {
      newErrors.traits = '最多只能添加3个角色特征'
    }

    // 验证特征
    formData.custom_traits?.forEach((trait, index) => {
      if (trait.key.length > 10) {
        newErrors[`trait_key_${index}`] = '特征名不能超过10字符'
      }
      if (trait.value.length > 50) {
        newErrors[`trait_value_${index}`] = '特征值不能超过50字符'
      }
    })

    setErrors(newErrors)
    return Object.keys(newErrors).length === 0
  }

  const handleSave = async () => {
    console.log('handleSave called, formData:', formData)
    
    const isValid = validateForm()
    console.log('Form validation result:', isValid)
    console.log('Current validation errors:', errors)
    
    if (!isValid) {
      console.log('Validation failed, not proceeding with save')
      alert('表单验证失败，请检查必填字段')
      return
    }

    console.log('Validation passed, proceeding with save...')
    setSaving(true)
    try {
      await onSave(formData)
      console.log('Save completed successfully')
    } catch (error) {
      console.error('Failed to save role:', error)
      alert('保存失败: ' + (error instanceof Error ? error.message : '未知错误'))
    } finally {
      setSaving(false)
    }
  }

  const handleTestRole = async () => {
    if (!testInput.trim()) {
      alert('请输入测试内容')
      return
    }

    setTestLoading(true)
    try {
      const response = await fetch('/api/roles/test', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name: formData.name,
          input_spec: formData.input_spec,
          output_spec: formData.output_spec,
          custom_traits: formData.custom_traits,
          input: testInput
        })
      })

      const data = await response.json()
      if (data.success) {
        setTestOutput(data.test_output || '测试完成，但没有返回结果')
      } else {
        setTestOutput('测试失败：' + (data.message || '未知错误'))
      }
    } catch (error) {
      console.error('Test role error:', error)
      setTestOutput('测试失败：' + (error instanceof Error ? error.message : '网络连接错误'))
    } finally {
      setTestLoading(false)
    }
  }

  const addTrait = () => {
    if (!formData.custom_traits || formData.custom_traits.length < 3) {
      setFormData(prev => ({
        ...prev,
        custom_traits: [...(prev.custom_traits || []), { key: '', value: '' }]
      }))
    }
  }

  const updateTrait = (index: number, field: 'key' | 'value', value: string) => {
    setFormData(prev => ({
      ...prev,
      custom_traits: prev.custom_traits?.map((trait, i) => 
        i === index ? { ...trait, [field]: value } : trait
      ) || []
    }))
  }

  const removeTrait = (index: number) => {
    setFormData(prev => ({
      ...prev,
      custom_traits: prev.custom_traits?.filter((_, i) => i !== index) || []
    }))
  }

  if (!isOpen) return null

  return (
    <div className={clsx('fixed inset-0 z-50 flex items-center justify-center', className)}>
      {/* 背景遮罩 */}
      <div 
        className="absolute inset-0 bg-black bg-opacity-50"
        onClick={onClose}
      />
      
      {/* 弹窗主体 */}
      <div className="relative bg-white rounded-lg shadow-xl w-full max-w-4xl max-h-[90vh] overflow-hidden">
        {/* 头部 */}
        <div className="flex items-center justify-between p-6 border-b border-gray-200">
          <h2 className="text-xl font-semibold text-gray-900">
            {editingRole ? '编辑角色' : '创建自定义角色'}
          </h2>
          <button
            onClick={onClose}
            className="text-gray-400 hover:text-gray-600 text-2xl font-bold"
          >
            ✕
          </button>
        </div>

        {/* 标签页 */}
        <div className="border-b border-gray-200">
          <nav className="flex space-x-8 px-6">
            <button
              onClick={() => setActiveTab('basic')}
              className={clsx(
                'py-3 px-1 border-b-2 font-medium text-sm',
                activeTab === 'basic'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              )}
            >
              基础信息
            </button>
            <button
              onClick={() => setActiveTab('traits')}
              className={clsx(
                'py-3 px-1 border-b-2 font-medium text-sm',
                activeTab === 'traits'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              )}
            >
              角色特征
            </button>
            <button
              onClick={() => setActiveTab('test')}
              className={clsx(
                'py-3 px-1 border-b-2 font-medium text-sm',
                activeTab === 'test'
                  ? 'border-blue-500 text-blue-600'
                  : 'border-transparent text-gray-500 hover:text-gray-700'
              )}
            >
              测试预览
            </button>
          </nav>
        </div>

        {/* 内容区 */}
        <div className="p-6 overflow-y-auto" style={{ maxHeight: 'calc(90vh - 180px)' }}>
          {/* 基础信息标签页 */}
          {activeTab === 'basic' && (
            <div className="space-y-6">
              {/* 角色名称和职业名称 */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-4">
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    角色名称 <span className="text-red-500">*</span>
                    <span className="text-xs text-gray-500 ml-2">给角色起个名字</span>
                  </label>
                  <input
                    type="text"
                    value={formData.name}
                    onChange={(e) => setFormData(prev => ({ ...prev, name: e.target.value }))}
                    placeholder="例如：小明的编程助手"
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  {errors.name && (
                    <p className="mt-1 text-sm text-red-600">{errors.name}</p>
                  )}
                </div>
                
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    职业/身份 <span className="text-red-500">*</span>
                    <span className="text-xs text-gray-500 ml-2">角色的职业身份</span>
                  </label>
                  <input
                    type="text"
                    value={formData.title}
                    onChange={(e) => setFormData(prev => ({ ...prev, title: e.target.value }))}
                    placeholder="例如：高级程序员"
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                  />
                  {errors.title && (
                    <p className="mt-1 text-sm text-red-600">{errors.title}</p>
                  )}
                </div>
              </div>

              {/* 输入输出规范 */}
              <div className="grid grid-cols-1 lg:grid-cols-2 gap-6">
                {/* 输入规范 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    输入规范 <span className="text-red-500">*</span>
                    <span className="text-xs text-gray-500 ml-2">这个角色接收什么？</span>
                  </label>
                  <textarea
                    value={formData.input_spec}
                    onChange={(e) => setFormData(prev => ({ ...prev, input_spec: e.target.value }))}
                    placeholder={`例如：
• 任何编程语言的代码
• 可以包含性能问题或bug
• 支持单个函数或完整文件`}
                    rows={6}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                  />
                  {errors.input_spec && (
                    <p className="mt-1 text-sm text-red-600">{errors.input_spec}</p>
                  )}
                  <p className="mt-1 text-xs text-gray-500">
                    {formData.input_spec.length}/800 字符
                  </p>
                </div>

                {/* 输出规范 */}
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    输出规范 <span className="text-red-500">*</span>
                    <span className="text-xs text-gray-500 ml-2">这个角色会返回什么？</span>
                  </label>
                  <textarea
                    value={formData.output_spec}
                    onChange={(e) => setFormData(prev => ({ ...prev, output_spec: e.target.value }))}
                    placeholder={`例如：
• 优化后的代码
• 性能改进说明
• 潜在问题提醒`}
                    rows={6}
                    className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 resize-none"
                  />
                  {errors.output_spec && (
                    <p className="mt-1 text-sm text-red-600">{errors.output_spec}</p>
                  )}
                  <p className="mt-1 text-xs text-gray-500">
                    {formData.output_spec.length}/800 字符
                  </p>
                </div>
              </div>

              {/* 系统提示词预览 */}
              {systemPromptPreview && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    系统提示词预览
                    <span className="text-xs text-gray-500 ml-2">约 {Math.ceil(systemPromptPreview.length / 4)} tokens</span>
                  </label>
                  <div className="bg-gray-50 border border-gray-200 rounded-md p-4 max-h-40 overflow-y-auto">
                    <pre className="text-sm text-gray-700 whitespace-pre-wrap">
                      {systemPromptPreview}
                    </pre>
                  </div>
                </div>
              )}
            </div>
          )}

          {/* 角色特征标签页 */}
          {activeTab === 'traits' && (
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-medium text-gray-900 mb-2">角色特征</h3>
                <p className="text-sm text-gray-600 mb-4">
                  添加最多3个特征来让角色更有个性（可选）
                </p>
              </div>

              {/* 特征列表 */}
              <div className="space-y-4">
                {formData.custom_traits?.map((trait, index) => (
                  <div key={index} className="flex gap-4 items-start p-4 border border-gray-200 rounded-lg">
                    <div className="flex-1">
                      <input
                        type="text"
                        value={trait.key}
                        onChange={(e) => updateTrait(index, 'key', e.target.value)}
                        placeholder="特征名（如：背景）"
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 mb-2"
                      />
                      <input
                        type="text"
                        value={trait.value}
                        onChange={(e) => updateTrait(index, 'value', e.target.value)}
                        placeholder="特征值（如：10年大厂经验）"
                        className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                      />
                      <div className="flex justify-between mt-1">
                        {errors[`trait_key_${index}`] && (
                          <p className="text-xs text-red-600">{errors[`trait_key_${index}`]}</p>
                        )}
                        {errors[`trait_value_${index}`] && (
                          <p className="text-xs text-red-600">{errors[`trait_value_${index}`]}</p>
                        )}
                        <p className="text-xs text-gray-500">
                          {trait.key.length}/10, {trait.value.length}/50
                        </p>
                      </div>
                    </div>
                    <button
                      onClick={() => removeTrait(index)}
                      className="text-red-500 hover:text-red-700 mt-2"
                    >
                      ✕
                    </button>
                  </div>
                ))}

                {/* 添加特征按钮 */}
                {(!formData.custom_traits || formData.custom_traits.length < 3) && (
                  <button
                    onClick={addTrait}
                    className="w-full flex items-center justify-center gap-2 p-4 border-2 border-dashed border-gray-300 rounded-lg hover:border-blue-300 hover:bg-blue-50 transition-all"
                  >
                    <span className="text-blue-600">➕</span>
                    <span className="text-sm font-medium text-blue-600">添加特征</span>
                  </button>
                )}
              </div>

              {/* 特征建议 */}
              <div>
                <h4 className="text-sm font-medium text-gray-700 mb-2">💡 特征建议</h4>
                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  {traitSuggestions.common.map((suggestion) => (
                    <div key={suggestion.key} className="bg-gray-50 p-3 rounded-lg">
                      <h5 className="text-sm font-medium text-gray-700">{suggestion.key}</h5>
                      <div className="mt-1 space-x-2">
                        {suggestion.examples.map((example) => (
                          <button
                            key={example}
                            onClick={() => {
                              if (!formData.custom_traits || formData.custom_traits.length < 3) {
                                setFormData(prev => ({
                                  ...prev,
                                  custom_traits: [...(prev.custom_traits || []), { key: suggestion.key, value: example }]
                                }))
                              }
                            }}
                            className="text-xs text-blue-600 hover:text-blue-800 underline"
                          >
                            {example}
                          </button>
                        ))}
                      </div>
                    </div>
                  ))}
                </div>
              </div>
            </div>
          )}

          {/* 测试预览标签页 */}
          {activeTab === 'test' && (
            <div className="space-y-6">
              <div>
                <h3 className="text-lg font-medium text-gray-900 mb-2">测试你的角色</h3>
                <p className="text-sm text-gray-600 mb-4">
                  输入测试内容，查看角色的回复效果
                </p>
              </div>

              {/* 测试输入 */}
              <div>
                <label className="block text-sm font-medium text-gray-700 mb-2">
                  测试输入
                </label>
                <textarea
                  value={testInput}
                  onChange={(e) => setTestInput(e.target.value)}
                  placeholder="输入测试内容..."
                  rows={4}
                  className="w-full px-3 py-2 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
              </div>

              {/* 测试按钮 */}
              <div className="flex justify-between items-center">
                <button
                  onClick={handleTestRole}
                  disabled={testLoading || !testInput.trim()}
                  className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
                >
                  {testLoading ? '测试中...' : '运行测试'}
                </button>
              </div>

              {/* 测试输出 */}
              {testOutput && (
                <div>
                  <label className="block text-sm font-medium text-gray-700 mb-2">
                    测试输出
                  </label>
                  <div className="bg-gray-50 border border-gray-200 rounded-md p-4 max-h-60 overflow-y-auto">
                    <pre className="text-sm text-gray-700 whitespace-pre-wrap">
                      {testOutput}
                    </pre>
                  </div>
                </div>
              )}
            </div>
          )}
        </div>

        {/* 底部按钮 */}
        <div className="border-t border-gray-200 px-6 py-4 flex justify-between">
          <button
            onClick={onClose}
            className="px-4 py-2 text-gray-600 bg-gray-100 rounded-md hover:bg-gray-200"
          >
            取消
          </button>
          <div className="flex gap-3">
            <button
              onClick={() => {
                console.log('Save button clicked')
                handleSave()
              }}
              disabled={saving}
              className="px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? '保存中...' : '保存角色'}
            </button>
            <button
              onClick={async () => {
                await handleSave()
                // TODO: 这里可以添加切换到该角色的逻辑
              }}
              disabled={saving}
              className="px-4 py-2 bg-green-600 text-white rounded-md hover:bg-green-700 disabled:opacity-50 disabled:cursor-not-allowed"
            >
              {saving ? '保存中...' : '保存并使用'}
            </button>
          </div>
        </div>
      </div>
    </div>
  )
}